package com.example.demo2.demo07;

import com.example.demo2.rabbitmq.RabbitMQConnection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 生产者 - 延时队列
 * 说明:
 * 1.将消息投递给延时交换机(delayed_exchange),延时交换机没有对应的消费者,进行等待(x-message-ttl)配置的时间,单位毫秒
 * 2.延时交换机将未消费的消息转投给死信交换机,死信交换机有对应的消费者,这时候死信消费者就会消费该消息。
 * 使用此方法达到延时队列的效果
 * @Author: mingtian
 * @CreateDate: 2021/1/18 09:25
 * @Version: 1.0
 */
public class Producer {
    /**
     * 打印日志
     */
    private static Logger logger = LoggerFactory.getLogger(Producer.class);


    /**
     * 延迟队列名称
     */
    private static final String DELAYED_QUEUE_NAME = "delayed_queue";

    /**
     * 延时交换机名称
     */
    private static final String DELAYED_EXCHANGE_NAME = "delayed_exchange";

    /**
     * 延时交换机路由 key
     */
    private static final String DELAYED_EXCHANGE_ROUTING_KEY = "delayed_routingKey";

    /**
     * 死信队列名称
     */
    private static final String DLX_QUEUE_NAME = "dlx_queue";

    /**
     * 死信交换机名称
     */
    private static final String DLX_EXCHANGE_NAME = "dlx_exchange";

    /**
     * 死信交换机路由key
     */
    private static final String DLX_EXCHANGE_ROUTING_KEY = "dlx_routingKey";

    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建一个新连接
        Connection connection = RabbitMQConnection.getConnection();
        //2.设置channel
        Channel channel = connection.createChannel();
        // 死信队列、交换机、路由键创建以及绑定
        // 声明交换机
        channel.exchangeDeclare(DLX_EXCHANGE_NAME, "direct", true);
        // 声明队列
        channel.queueDeclare(DLX_QUEUE_NAME, true, false, false, null);
        // 队列与交换机绑定
        channel.queueBind(DLX_QUEUE_NAME, DLX_EXCHANGE_NAME, DLX_EXCHANGE_ROUTING_KEY);

        // 延时队列、交换机、路由键创建以及绑定
        // 声明交换机
        channel.exchangeDeclare(DELAYED_EXCHANGE_NAME, "direct", true);
        Map<String, Object> arguments = new HashMap<>(2);
        arguments.put("x-message-ttl", 10000);        // 配置延时 10s
        arguments.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);// 配置死信交换机
        arguments.put("x-dead-letter-routing-key", DLX_EXCHANGE_ROUTING_KEY);// 配置死信交互机路由key
        // 声明队列
        channel.queueDeclare(DELAYED_QUEUE_NAME, true, false, false, arguments);
        // 队列与交换机绑定
        channel.queueBind(DELAYED_QUEUE_NAME, DELAYED_EXCHANGE_NAME, DELAYED_EXCHANGE_ROUTING_KEY);
        //3.发送消息
        String msg = "hello,this is a msg";
        channel.basicPublish(DELAYED_EXCHANGE_NAME, DELAYED_EXCHANGE_ROUTING_KEY, null, msg.getBytes());
        logger.info("投递消息成功");
        channel.close();
        connection.close();
    }
}
